import { useState, useEffect } from 'react';
import DOMObserver from './DOMObserver';

/**
 * IFrame处理组件
 * @param {Object} props
 * @param {string} props.containerSelector - 包含iframe的容器选择器
 * @param {Function} props.onIFrameReady - iframe准备好时的回调函数
 * @param {number} props.targetIndex - 目标iframe的索引，默认为0
 * @param {string} props.displayFilter - 显示过滤条件，例如'block'
 * @returns {Object} iframe相关状态
 */
const IFrameHandler = ({
  containerSelector = '.main-container-view',
  onIFrameReady,
  targetIndex = 0,
  displayFilter
}) => {
  const [iframeDocument, setIframeDocument] = useState(null);
  const [isReady, setIsReady] = useState(false);

  // 处理iframe加载
  const handleIFrameLoad = (iframe) => {
    return () => {
      const iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
      setIframeDocument(iframeDoc);
      setIsReady(true);
      
      if (onIFrameReady) {
        onIFrameReady(iframeDoc, iframe);
      }
    };
  };

  // 处理容器变化
  const handleContainerChange = (container) => {
    if (!container) return;
    
    const iframeDomList = document.querySelectorAll('iframe');
    
    iframeDomList.forEach((iframe, index) => {
      // 如果有显示过滤条件，检查iframe是否符合条件
      if (displayFilter) {
        const computedStyle = window.getComputedStyle(iframe);
        const displayValue = computedStyle.display;
        
        if (displayValue !== displayFilter) return;
      }
      
      // 如果指定了目标索引，只处理该索引的iframe
      if (targetIndex !== undefined && index !== targetIndex) return;
      
      // 设置iframe加载事件
      iframe.onload = handleIFrameLoad(iframe);
      
      // 如果iframe已经加载完成，手动触发加载事件
      if (iframe.contentDocument && iframe.contentDocument.readyState === 'complete') {
        handleIFrameLoad(iframe)();
      }
    });
  };

  return (
    <DOMObserver
      target={containerSelector}
      callback={handleContainerChange}
      options={{ childList: true, subtree: true }}
    />
  );
};

export default IFrameHandler;